import minappSdk from "minapp-sdk"
import { cryptoDecode, cryptoEncode } from "@/utils/crypto"
import { message } from "ant-design-vue"
import axios from "axios"
import { getToken } from "@/utils/auth"
import { ResponsePromiseData } from "@/types"
// tables
let userTabel = new minappSdk.TableObject("user")

/**
 * 登录
 * @description 前后端不分离，无token自动，使用id进行mock为token
 * @returns
 */
async function login<T>(formState: any): ResponsePromiseData<T> {
  let query = new minappSdk.Query()
  query.compare("username", "=", formState.username)
  try {
    let {
      data: { objects }
    } = await userTabel.setQuery(query).find()
    if (objects.length) {
      if (cryptoDecode(objects[0].password) == formState.password) {
        return { code: 0, message: "登录成功", data: { token: objects[0].id } as any }
      }
      throw new Error("密码不正确，请重试！")
    } else {
      throw new Error("账号不存在，请重试！")
    }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

/**
 * 获取用户信息
 * @param recordId {string } 本项目无后端，需取id发挥作用
 * @returns
 */
async function getUserInfo<T>(): ResponsePromiseData<T> {
  let recordId = getToken()
  if (!recordId) throw new Error("获取失败")
  try {
    let { data } = await userTabel.get(recordId)
    return { code: 0, message: "获取成功", data }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 发送验证码
async function sendCaptcha<T>(params: any): ResponsePromiseData<T> {
  //补充参数
  params.platformName = "闽南药膳库服务平台"
  params.isEncrypted = 0
  try {
    let { data } = await axios.post("/send_captcha/utils/captcha", params)
    console.log("验证码", data)
    if (data.code != 0) {
      throw data.message
    }
    // 将验证码存储于本地(加密形态，有效期15min)
    let content = {
      expiration: Date.now() + 15 * 60 * 1000,
      value: cryptoEncode(data.data.captcha)
    }
    sessionStorage.setItem("captcha", JSON.stringify(content))

    return { code: 0, message: "发送成功" }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 注册
async function register<T>(formState: any): ResponsePromiseData<T> {
  try {
    // 1.核对验证码
    let storagedCaptcha: any = sessionStorage.getItem("captcha")
    if (!storagedCaptcha) {
      throw new Error("验证码不存在")
    }
    storagedCaptcha = JSON.parse(storagedCaptcha)
    console.log("storagedCaptcha", storagedCaptcha)

    if (storagedCaptcha!.expiration < Date.now()) {
      throw new Error("验证码已失效")
    }
    const decodeCaptcha = cryptoDecode(storagedCaptcha!.value)
    console.log("decodeCaptcha", decodeCaptcha)
    if (decodeCaptcha !== formState.captcha) {
      throw new Error("验证码不正确")
    }

    let { data } = await getUserRecord(formState.username)
    if (data.length) {
      throw new Error("账号已存在")
    }
    // 2.信息处理
    formState.password = cryptoEncode(formState.password)
    formState.roles = ["user"]

    let MyRecord = userTabel.create()
    MyRecord.set(formState)
    await MyRecord.save()
    return { code: 0, message: "注册成功" }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 重置密码
async function resetPassword<T>(formState: any): ResponsePromiseData<T> {
  try {
    // 1. 判断用户是否cunz
    let { data } = await getUserRecord(formState.username)
    console.log(data)
    if (!data.length) {
      throw new Error("账号不存在")
    }
    // 2.核对验证码
    let storagedCaptcha: any = sessionStorage.getItem("captcha")
    if (!storagedCaptcha) {
      throw new Error("验证码不存在")
    }
    storagedCaptcha = JSON.parse(storagedCaptcha)

    if (storagedCaptcha!.expiration < Date.now()) {
      throw new Error("验证码已失效")
    }
    const decodeCaptcha = cryptoDecode(storagedCaptcha!.value)
    if (decodeCaptcha !== formState.captcha) {
      throw new Error("验证码不正确")
    }
    // 2.信息处理
    formState.password = cryptoEncode(formState.password)

    let record = userTabel.getWithoutData(data[0]._id)
    record.set("password", formState.password)
    await record.update()
    return { code: 0, message: "重置成功" }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 查询用户(用户名)
export async function getUserRecord(username: string) {
  let query = new minappSdk.Query()
  query.compare("username", "=", username)
  try {
    let res = await userTabel.setQuery(query).find()
    return { code: 0, message: "获取成功", data: res.data.objects }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 根据id获取用户信息
async function getUserInfoById<T>(id: string): ResponsePromiseData<T> {
  try {
    let { data } = await userTabel.get(id)
    return { code: 0, message: `获取成功`, data }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 根据角色查找用户
async function getUserByRole<T>(roles: string[]): ResponsePromiseData<T> {
  let query = new minappSdk.Query()
  query.arrayContains("roles", roles)

  let result: any = []
  let offset = 0
  while (true) {
    try {
      let res = await userTabel.setQuery(query).limit(1000).offset(offset).find({ withCount: true })
      result = result.concat(res.data.objects)
      offset += 1000
      let total = res.data.meta.total_count
      if (result.length >= total) break
    } catch (error: any) {
      message.error(error.message)
      return Promise.reject(error.message)
    }
  }
  return { code: 0, data: result, message: "获取成功" }
}

// 新增用户
async function addUser(formState: any): ResponsePromiseData {
  try {
    let { data } = await getUserRecord(formState.username)
    if (data.length) {
      throw new Error("账号已存在")
    }
    formState.password = cryptoEncode(formState.password)
    formState.roles = ["user"]

    let MyRecord = userTabel.create()
    MyRecord.set(formState)
    await MyRecord.save()
    return { code: 0, message: "新增成功" }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

//更新用户
async function updateUser(id: string, formState: any): ResponsePromiseData {
  console.log(id, formState)
  try {
    let record = userTabel.getWithoutData(id)
    record.set({ ...formState })
    await record.update()
    return { code: 0, message: "更新成功" }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 删除用户
async function deleteUser(id: string) {
  try {
    await userTabel.delete(id)
    return { code: 0, message: "删除成功" }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 获取用户列表(分页)
async function getUserList<T>(page: number = 1, pageSize: number = 10, searchQuery: any = null): ResponsePromiseData<T> {
  const offset: number = (page - 1) * pageSize
  let query = new minappSdk.Query()
  if (searchQuery?.constructor === Object) {
    for (let key in searchQuery) {
      query.contains(key, searchQuery[key]) //模糊搜索
      // query.compare(key, "=", searchQuery[key])
    }
  }
  try {
    const {
      data: {
        meta: { total_count },
        objects
      }
    } = await userTabel.setQuery(query).limit(pageSize).offset(offset).find({ withCount: true })

    return { code: 0, data: { list: objects, total: total_count } as T, message: "获取成功" }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}
export default {
  login,
  getUserInfo,
  sendCaptcha,
  register,
  getUserInfoById,
  getUserByRole,
  updateUser,
  deleteUser,
  getUserList,
  addUser,
  resetPassword
}
